# -*- coding: utf-8 -*-
# Copyright Š 2010 alexliyu
#
# This file is part of cntop-news.
#
# cntop-news is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cntop-news is base on Top-news-buzz ,
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cntop-news.  If not, see <http://www.gnu.org/licenses/>.
import re

from django.template.defaultfilters import stringfilter

from google.appengine.ext import webapp

from topnewsbuzz.lib.BeautifulSoup import BeautifulSoup, Comment

register = webapp.template.create_template_register()

def replace(string, args):
    '''This will perform a regular expression search/replace on a string in your template.
    {% load replace %} {{ mystring|replace:"/l(u+)pin/m\1gen" }}
    If: mystring = 'lupin, luuuuuupin, and luuuuuuuuuuuuupin are lè pwn' then it will return: mugen, muuuuuugen, and muuuuuuuuuuuuugen are lè pwn
    The argument is in the following format:
    [delim char]regexp search[delim char]regexp replace
    Idea taken from: http://www.djangosnippets.org/snippets/60/
    ''' 
    search  = unicode(args.split(args[0])[1], 'utf-8')
    replace = unicode(args.split(args[0])[2], 'utf-8')

    return re.sub(search, replace, string)

def sanitize(value, valid_tags_arg = 'p i strong b u a h1 h2 h3 pre br img'):
    """
    Idea taken from: http://www.djangosnippets.org/snippets/205/
    """
    valid_tags = valid_tags_arg.split()
    valid_attrs = 'href src'.split()
    soup = BeautifulSoup(value)
    for comment in soup.findAll(
        text=lambda text: isinstance(text, Comment)):
        comment.extract()
    for tag in soup.findAll(True):
        if tag.name not in valid_tags:
            tag.hidden = True
        tag.attrs = [(attr, val) for attr, val in tag.attrs
                     if attr in valid_attrs]
    return soup.renderContents().decode('utf8').replace('javascript:', '')

register.filter(replace)
register.filter(sanitize)
